// 用户注册登录处理函数模块

const db = require('../db')

// const path = require('path')

const bcrypt = require('bcryptjs')

const JWT = require('jsonwebtoken')

const config = require('../config.js')

// 用户注册处理函数
exports.regUser = (req, res) => {
  const sql = 'select * from user where phone=?'
  const body = {
    ...req.body,
    img: 'http://127.0.0.1:8000/upload/image/img_1660464010198.jpg'
  }
  body.password = bcrypt.hashSync(body.password, 10)
  db.query(sql, body.phone, (err, results) => {
    if (err) {
      return res.ss(err)
    }
    if (results.length >= 1) {
      return res.ss('手机号已注册！')
    }
    const sql = 'insert into user set ?'
    db.query(sql, body, (err, results) => {
      if (err) {
        return res.ss(err)
      }
      if (results.affectedRows !== 1) {
        return res.ss('注册用户失败！')
      }
      res.ss('注册用户成功！', 200)
    })
  })
}

// 登录用户处理函数
exports.loginUser = (req, res) => {
  const body = req.body
  const sql = 'select * from user where phone=?'
  if (!body.phone || !body.password) {
    return res.ss('手机号码或密码不能为空！')
  }
  db.query(sql, body.phone, (err, results) => {
    if (err) {
      return res.ss(err)
    }
    if (results.length !== 1) {
      return res.ss('无此用户！')
    }
    const compareResult = bcrypt.compareSync(body.password, results[0].password)
    if (!compareResult) {
      return res.ss('密码不正确！')
    }
    // 将对象展开，并设置 password 属性值为空字符串
    const user = { ...results[0], password: '' }
    const token = JWT.sign(user, config.jwtSecretKey, { expiresIn: '1h' })
    console.log(user)
    res.send({
      state: 200,
      message: '登录用户成功！',
      data: results[0],
      token: 'Bearer ' + token
    })
  })
}

// 找回用户密码处理函数
exports.retrievePassword = (req, res) => {
  const body = req.body
  const sql = 'select * from user where phone=?'
  body.password = bcrypt.hashSync(body.password, 10)
  db.query(sql, body.phone, (err, results) => {
    if (err) {
      return res.ss(err)
    }
    if (results.length <= 0) {
      return res.ss('手机号码不正确或无该用户！')
    }
    const sql = 'update user set ? where phone=?'
    db.query(sql, [body, body.phone], (err, results) => {
      if (err) {
        return res.ss(err)
      }
      if (results.affectedRows !== 1) {
        return res.ss('修改密码失败！')
      }
      res.ss('修改密码成功！', 200)
    })
  })
}
